package com.kaifamiao.month04.day26;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Date;

public class DateUtils {

    static final String DATE_PATTERN = "yyyy年MM月dd日 hh:mm:ss";

    private final Date date = new Date();

    public String dateFormat(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        return sdf.format(date);
    }

    public String dateFormat(Date date, String pattern) {
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        return sdf.format(date);
    }

    public String dateFormat() {
        return dateFormat(date,DATE_PATTERN);
    }

    public Date formatDate(String str) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        return sdf.parse(str);
    }

    public Date formatDate(String str, String pattern) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        return sdf.parse(str);
    }

    public Date formatDate() {
        return null;
    }

    public Date plusDays(int day) {
        LocalDate ld = transform(date);
        ld = ld.plusDays(day);
        return transform(ld);
    }

    public Date minusDays(int day) {
        LocalDate ld = transform(date);
        ld = ld.minusDays(day);
        return transform(ld);
    }

    private LocalDate transform(Date date) {
        Instant instant = date.toInstant();
        ZoneId zoneId = ZoneId.systemDefault();
        ZonedDateTime zdt = instant.atZone(zoneId);
        return zdt.toLocalDate();
    }

    private Date transform(LocalDate ld) {
        ZoneId zoneId = ZoneId.systemDefault();
        ZonedDateTime zdt = ZonedDateTime.of(ld.atStartOfDay(), zoneId);
        Instant instant = zdt.toInstant();
        return Date.from(instant);
    }

    public int getAge(Date birth) {
        LocalDate now = transform(date);
        LocalDate bld = transform(birth);
        return now.compareTo(bld);
    }

    public String getBirth(int age) {
        LocalDate now = transform(date);
        LocalDate bld = now.minusYears(age);
        Date birth = transform(bld);
        return dateFormat(birth,"yyyy年MM月");
    }

}
